<?php

namespace app\admin\controller\fittings;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 配件分类
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{

    /**
     * Category模型对象
     * @var \app\common\model\fittings\Category
     */
    protected $model = null;
    protected $categorylist = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\fittings\Category;
        $this->categorylist = collection($this->model->select())->toArray();
        $tree = Tree::instance();
        $tree->init($this->categorylist, 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'title');
        $categorylist = $this->model->where('pid',0)->select();
        $this->view->assign("categorylist", $categorylist);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $search = $this->request->request("search");
            $type = $this->request->request("type");

            //构造父类select列表选项数据
            $list = [];

            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['title'], $search) !== false) {
                        if ($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function selectpage()
    {
        return parent::selectpage();
    }

    public function ajax()
    {
        $pid = $this->request->get('pid', '');
        $where = [];
        $categorylist = null;
        if ($pid || $pid === '0') {
            $where['pid'] = $pid;
        }

        $categorylist = $this->model->where($where)->field('id as value,title as name')->select();

        $this->success('', '', $categorylist);
    }
}
